//
//  UrlParseUtility.swift
//  Demo
//
//  Created by 章旭松 on 16/8/31.
//  Copyright © 2016年 章旭松. All rights reserved.
//

import Foundation

extension String {
    func getScheme() -> String? {
        return NSURLComponents(string: self)?.scheme
    }
    
    func getHost() -> String? {
        return NSURLComponents(string: self)?.host
    }
    
    func getQueryParameter(key key: String) -> String? {
        
        let urlItem = NSURLComponents(string: self)?.queryItems?.filter({ (item) -> Bool in
            return item.name == key
        }).first
        return urlItem?.value
    }
    
    func appendQueryParameter(key key: String, value: String) -> String {
        guard let components = NSURLComponents(string: self) else {
            return self
        }
        let item = NSURLQueryItem(name:key, value: value)
        if let _ = components.queryItems {
            components.queryItems?.append(item)
        } else {
            components.queryItems = [item]
        }
        if let url = components.URL?.absoluteString {
            return url
        } else {
            return self
        }
    }
    
    func urlEncode() -> String? {
        let unreservedChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-!.~'()*"
        let unreservedCharset = NSCharacterSet(charactersInString: unreservedChars)
        let encodedString = stringByAddingPercentEncodingWithAllowedCharacters(unreservedCharset)
        return encodedString
    }
    
    func appendQueryParameterUseEncode(key key: String, value: String) -> String {
        guard let components = NSURLComponents(string: self), url = components.URL, encodedValue = value.urlEncode() else {
            return self
        }
        if let queryItems = components.queryItems { // 带参数
            if (queryItems.count > 0) && !url.absoluteString.hasSuffix("&") {
                return url.absoluteString + "&" + key + "=" + encodedValue
            } else { // 带问号，但没有参数
                return url.absoluteString + key + "=" + encodedValue
            }
        } else { // 不带参数
            return url.absoluteString + "?" + key + "=" + encodedValue
        }
    }
}
